package main

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os"
	"time"
)

type ContentData struct {
	Content string `json:content`
}

func main() {
	l, err := net.Listen("tcp4", "localhost:8080")
	if err != nil {
		panic(err)
	}
	num := 1
	prefix := time.Now().Format("20060102150405")
	http.HandleFunc("/content", func(w http.ResponseWriter, r *http.Request) {
		log.Println("POST /content")

		data, err := io.ReadAll(r.Body)
		if err != nil {
			w.WriteHeader(404)
			log.Println("read body nil")
			return
		}

		content := ContentData{}
		err = json.Unmarshal(data, &content)
		if err != nil {
			w.WriteHeader(404)
			log.Println("json body format error:")
			os.Stdout.Write(data)
			log.Println("==end==")
			return
		}

		name := fmt.Sprintf("%v-%04d.txt", prefix, num)
		num++

		ioutil.WriteFile(name, []byte(content.Content+"\n\n"), 0644)
		log.Println("save ", name)

		w.WriteHeader(200)
	})

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Println("POST /")
		w.WriteHeader(200)
	})

	fmt.Println("start server at localhost:8080")
	err = http.Serve(l, nil)
	if err != nil {
		panic(err)
	}
}
